import grace from "../../utils/grace.js"
import config from "../../utils/config.js"
grace.page({
      data: {
            timer: null,
            maxtime: 10,
            btnSend: '发送验证码',
            mobile: '',
            code: '',
      },
      onLoad: function(options) {
            let that = this;
            that.$data.timer = setInterval(function() {
                  that.count_timer();
                  console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
            }, 1000);
      },
      wxSearchInput: function(e) {
            var value = e.detail.value;
            var item = e.target.dataset.item;
            this.$data[item] = value;
      },
      doSubmit: function() {
            if (this.data.code.length == 0) {
                  this.toast('请填写验证码！');
                  return;
            }
            let that = this;
            let param = {
                  mobile: this.data.mobile,
                  code: this.data.code
            };
            that.$http.post('api/sms/verify', param).then((res) => {
                  that.$http.post('api/user/binding_mobile', param).then((res) => {
                        that.toast('操作成功！');
                  });
            });
      },
      sendCode: function(e) {
            if (this.$data.timer != null) return;
            if (this.data.mobile.length == 0) {
                  this.toast('请输入手机号码');
                  return;
            }
            let params = {
                  mobile: this.data.mobile,
                  send_source: 'weixin',
                  api_secret: config.apiSecret
            };
            let that = this;
            this.$http.post('api/sms/send_verify', params).then((res) => {
                  that.toast('验证码发送成功');
                  that.$data.timer = wx.setInterval(function() {
                        that.count_timer();
                  }, 1000);
            });
      },
      count_timer: function(e) {
            if (this.$data.maxtime >= 0) {
                  this.$data.btnSend = '等待' + this.$data.maxtime + 's';
                  this.$data.maxtime = this.$data.maxtime - 1;
            } else {
                  clearInterval(this.$data.timer);
                  this.$data = {
                        btnSend: '发送验证码',
                        maxtime: 60,
                        timer: null
                  };
            }
      }
})